﻿using System.Reflection;

namespace Newtonsoft.Json.Serialization
{
    public class StringValueProvider : ExpressionValueProvider, IValueProvider
    {
        private readonly bool _isConvertNullToEmpty;

        public StringValueProvider(MemberInfo member, bool isConvertNullToEmpty)
            : base(member)
        {
            var type = Dyao.Book.Core.ReflectionHelper.GetMemberUnderlyingType(member);
            if (type != typeof(string))
            {
                throw new ArgumentException("This value provider can only be used with string type.");
            }

            this._isConvertNullToEmpty = isConvertNullToEmpty;
        }

        public new object GetValue(object target)
        {
            var value = base.GetValue(target);

            if (_isConvertNullToEmpty && value == null)
            {
                return string.Empty;
            }

            return value;
        }

        public new void SetValue(object target, object value)
        {
            base.SetValue(target, value);
        }
    }
}
